package io.gitee.thinkbungee.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.gitee.thinkbungee.entity.ColumnEntity;
import io.gitee.thinkbungee.entity.TableEntity;
import io.gitee.thinkbungee.entity.mongo.MongoDefinition;
import io.gitee.thinkbungee.entity.mongo.MongoGeneratorEntity;
import io.gitee.thinkbungee.utils.mongo.MongoManager;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成的工具类
 *
 * @author chenyichang
 * @date 2022/3/14
 */
public class GeneratorUtils {

    private static final Logger log = LoggerFactory.getLogger(GeneratorUtils.class);

    //mongo表 子类的生成会使用到
    private static String currentTableName;

    /**
     * 通用的生成代码
     * <p>
     * mongo表列名是 驼峰风格   userName
     * mysql表列名是 下划线风格 user_name
     * <p>
     * <p>
     * 所以在处理entity时等其他实体类时需要注意
     * {@link GeneratorUtils#columnToJava(String)}是以下划线的后一位大写，其他小写
     * mysql就使用{@link ColumnEntity#getAttrNameC()}
     * mongo就使用{@link ColumnEntity#getColumnName()}}
     * 比如 生成的 ColumnEntity
     * mysql：
     * {
     * "attrNameC": "CreateTime",
     * "attrNameUnC": "createTime",
     * "attrType": "Date",
     * "columnName": "create_time",
     * "comment": "创建时间",
     * "dataType": "timestamp",
     * "extra": ""
     * }
     * mongo：
     * {
     * "attrNameC": "Createtime",
     * "attrNameUnC": "createtime",
     * "attrType": "Date",
     * "columnName": "createTime",
     * "comment": "",
     * "dataType": "DATE",
     * "extra": ""
     * }
     *
     * @param table   表信息
     * @param columns 列名信息
     * @param zos     生成的代码放入输出流信息
     */
    public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zos) {
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        boolean hasList = false;

        //表
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComment(table.get("tableComment"));

        //名字转为class名
        String className = tableToJava(tableEntity.getTableName(), config.getStringArray("tablePrefix"));
        tableEntity.setClassNameC(className);//大写
        tableEntity.setClassNameUnC(StringUtils.uncapitalize(className));//小写

        //列
        List<ColumnEntity> columnEntityList = new ArrayList<>();
        tableEntity.setColumns(columnEntityList);

        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setComment(column.get("columnComment"));
            columnEntity.setExtra(column.get("extra"));
            //列名 转换为属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrNameC(attrName);//大写
            columnEntity.setAttrNameUnC(StringUtils.uncapitalize(attrName));//小写

            //列的数据类型，转为java类型
            String attrType = config.getString(columnEntity.getDataType(),
                    columnToJava(columnEntity.getDataType()));
            columnEntity.setAttrType(attrType);

            if (!hasBigDecimal && StringUtils.equals(attrType, "BigDecimal")) {
                hasBigDecimal = true;
            }
            if (!hasList && StringUtils.equals(columnEntity.getExtra(), "array")) {
                hasList = true;
            }
            //是否是主键
            if (StringUtils.equalsIgnoreCase("pri", column.get("columnKey"))
                    && tableEntity.getPrimaryKey() == null) {
                tableEntity.setPrimaryKey(columnEntity);
            }
            columnEntityList.add(columnEntity);
        }

        //如果没有主键，则设置第一个字段为主键
        if (tableEntity.getPrimaryKey() == null) {
            tableEntity.setPrimaryKey(tableEntity.getColumns().get(0));
        }

        //使用velocity资源加载
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        Map<String, Object> map = new HashMap();
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("hasList", hasList);

        //封装模板数据
        wrapperPropertiesData(map, config, tableEntity);

        //获取模板
        List<String> templates = getTemplates(config.getString("template", "mybatis"));

        VelocityContext context = new VelocityContext(map);


        String packageName = config.getString("package");
        String moduleName = config.getString("moduleName");
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            //添加到流中
            try {
                zos.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassNameC(),
                        packageName, moduleName)));
                IOUtils.write(sw.toString(), zos, "UTF-8");
                IOUtils.closeQuietly(sw);
                zos.closeEntry();
            } catch (Exception e) {
                throw new RuntimeException("渲染模板失败:" + tableEntity.getTableName(), e);
            }
        }
    }

    /**
     * 通过不同的模板得到相应的文件路径名
     *
     * @param template    模板
     * @param className   类名
     * @param packageName 包名
     * @param moduleName  模块名
     * @return
     */
    private static String getFileName(String template, String className, String packageName, String moduleName) {
        //包名 + 模块名
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator)
                    + File.separator + moduleName
                    + File.separator;
        }
        //工具类
        if (template.contains("QueryUtils.java.vm")) {
            return packagePath + "utils"
                    + File.separator + "QueryUtils.java";
        }

        //mongoChildren 实体类包含对象的
        if (template.contains("MongoChildrenEntity.java.vm")) {
            return packagePath + "entity"
                    + File.separator + className.replaceAll("\\.", "_")
                    + "java";
        }

        if (template.contains("Entity.java.vm") || template.contains("MongoEntity.java.vm")) {
            return packagePath + "entity"
                    + File.separator + className + "Entity.java";
        }

        if (template.contains("Mapper.java.vm")) {
            return packagePath + "dao"
                    + File.separator + className + "Mapper.java";
        }
        if (template.contains("Dao.java.vm")) {
            return packagePath + "dao"
                    + File.separator + className + "Dao.java";
        }

        if (template.contains("Service.java.vm")) {
            return packagePath + "service"
                    + File.separator + className + "Service.java";
        }
        if (template.contains("ServiceImpl.java.vm")) {
            return packagePath + "service"
                    + File.separator + "impl"
                    + File.separator + className + "ServiceImpl.java";
        }
        if (template.contains("Controller.java.vm")) {
            return packagePath + "controller"
                    + File.separator + className + "Controller.java";
        }
        if (template.contains("Dto.java.vm")) {
            return packagePath + "controller"
                    + File.separator + "dto"
                    + File.separator + className + "Dto.java";
        }
        if (template.contains("Param.java.vm")) {
            return packagePath + "controller"
                    + File.separator + "param"
                    + File.separator + className + "Param.java";
        }
        if (template.contains("Mapper.xml.vm")) {
            return "main"
                    + File.separator + "resources"
                    + File.separator + "mapper"
                    + File.separator + moduleName
                    + File.separator + className + "Mapper.xml";
        }
        if (template.contains("Dao.xml.vm")) {
            return "main"
                    + File.separator + "resources"
                    + File.separator + "mapper"
                    + File.separator + moduleName
                    + File.separator + className + "Dao.xml";
        }

        if (template.contains("index.vue.vm")) {
            return "main"
                    + File.separator + "resources"
                    + File.separator + "src"
                    + File.separator + "views"
                    + File.separator + "modules"
                    + File.separator + moduleName
                    + File.separator + className.toLowerCase() + ".vue";
        }
        if (template.contains("add-or-update.vue.vm")) {
            return "main"
                    + File.separator + "resources"
                    + File.separator + "src"
                    + File.separator + "views"
                    + File.separator + "modules"
                    + File.separator + moduleName
                    + File.separator + className.toLowerCase() + "-add-or-update.vue";
        }

        return null;
    }

    /**
     * 获取所有模板
     * 1.mybatis通用版
     * 2.mybatisSatellite升级版
     * 3.mongoSatellite升级版
     *
     * @return
     */
    private static List<String> getTemplates(String template) {
        log.info("使用{}模板", template);

        List<String> templates = new ArrayList<>();
        template = "template-" + template + File.separator;
//        //生成权限的SQL语句
//        templates.add(template + "menu.sql.vm");

        //service层
        templates.add(template + "Service.java.vm");
        templates.add(template + "ServiceImpl.java.vm");

        //controller层
        templates.add(template + "Controller.java.vm");

        //前端
        //展示vue
        templates.add(template + "index.vue.vm");
        //增删改查vue
        templates.add(template + "add-or-update.vue.vm");

        if (StrUtil.contains(template, "mybatisSatellite")) {
            //添加自定义的mapper
            templates.add(template + "Mapper.java.vm");
            templates.add(template + "Mapper.xml.vm");
            //controller层的param和dto
            templates.add(template + "Dto.java.vm");
            templates.add(template + "Param.java.vm");
        } else if (StrUtil.contains(template, "mongoSatellite")) {
            if (MongoManager.isMongo()) {
                //自己的entity
                templates.add(template + "MongoEntity.java.vm");
                //controller层的param和dto
                templates.add(template + "Dto.java.vm");
                templates.add(template + "Param.java.vm");
            }
        } else {
            templates.add(template + "QueryUtils.java.vm");
        }

        return templates;
    }


    /**
     * 把配置中的值放入map中
     *
     * @param map         数据
     * @param config      配置
     * @param tableEntity 表信息
     */
    private static void wrapperPropertiesData(Map<String, Object> map, Configuration config, TableEntity tableEntity) {
        String mainPath = config.getString("mainPath");
        mainPath = StringUtils.isBlank(mainPath) ? "io.gitee.thinkbungee" : mainPath;
        map.put("mainPath", mainPath);

        map.put("tableName", tableEntity.getTableName());
        map.put("comment", tableEntity.getComment());
        map.put("pk", tableEntity.getPrimaryKey());
        map.put("classNameC", tableEntity.getClassNameC());
        map.put("classNameUnC", tableEntity.getClassNameUnC());
        map.put("pathName", tableEntity.getClassNameC().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("package", config.getString("package"));
        map.put("moduleName", config.getString("moduleName"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtil.formatDateTime(new Date()));
    }

    /**
     * 表名转换为java类名
     *
     * @param tableName     表名
     * @param tablePrefixes 表前缀
     * @return
     */
    private static String tableToJava(String tableName, String[] tablePrefixes) {
        //如果配置中有写前缀，就将前缀给删掉
        if (null != tablePrefixes && tablePrefixes.length > 0) {
            for (String tablePrefix : tablePrefixes) {
                if (tableName.startsWith(tablePrefix)) {
                    tableName = tableName.replaceFirst(tablePrefix, "");
                }
            }
        }
        return columnToJava(tableName);
    }

    /**
     * 列名转java类名
     * <p>
     * 下划线转驼峰命名风格 hutool工具类
     * StrUtil.toCamelCase(columnName);
     * <p>
     * apache common 工具类会有空指针异常，但是很灵活，按照指定分割值来转大写
     * 规则如下: "_"后面的字符大写,首字母大写,其余字符小写
     * username==>Username
     * user_naME==>UserName
     *
     * @param columnName 列名
     * @return
     */
    private static String columnToJava(String columnName) {

        return WordUtils.capitalizeFully(columnName, new char[]{'_'})
                .replace("_", "");
    }


    /**
     * 获取配置信息
     */
    private static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (Exception e) {
            throw new RuntimeException("获取配置文件失败", e);
        }
    }


    /**
     * 生成mongo其他实体类的代码
     */
    public static void generatorMongoCode(String[] tableNames, ZipOutputStream zos) {
        for (String tableName : tableNames) {
            MongoDefinition info = MongoManager.getInfo(tableName);
            currentTableName = tableName;
            List<MongoGeneratorEntity> childrenInfo = info.getChildrenInfo(tableName);
            //移除第一个元素，该元素是该table，已经生成过了
            childrenInfo.remove(0);
            for (MongoGeneratorEntity entity : childrenInfo) {
                generatorMongoChildrenCode(entity, zos);
            }
        }
    }

    /**
     * 生成mongo表中的子类实体
     *
     * @param entity 子类表信息
     * @param zos    返回的压缩包
     * @see GeneratorUtils#generatorCode(Map, List, ZipOutputStream)
     */
    private static void generatorMongoChildrenCode(MongoGeneratorEntity entity, ZipOutputStream zos) {
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        boolean hasList = false;

        //表信息
        TableEntity tableEntity = entity.toTableEntity();
        //表名转java类名
        String className = tableToJava(tableEntity.getTableName(), config.getStringArray("tablePrefix"));
        tableEntity.setClassNameC(className);//大写
        tableEntity.setClassNameUnC(StringUtils.uncapitalize(className));//小写
        //列信息
        List<ColumnEntity> columnEntityList = new ArrayList<>();
        for (Map<String, String> column : entity.getColumns()) {
            ColumnEntity columnEntity = new ColumnEntity();
            String columnName = column.get("columnName");
            if (columnName.contains(".")) {
                columnName = columnName.substring(columnName.lastIndexOf(".") + 1);
            }
            columnEntity.setColumnName(columnName);
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setExtra(column.get("extra"));

            //列名转java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrNameC(attrName);
            columnEntity.setAttrNameUnC(StringUtils.uncapitalize(attrName));

            //列的数据类型，转为java类型
            String attrType = config.getString(columnEntity.getDataType(), columnToJava(columnEntity.getDataType()));
            columnEntity.setAttrType(attrType);

            if (!hasBigDecimal && StringUtils.equals(attrType, "BigDecimal")) {
                hasBigDecimal = true;
            }
            if (!hasList && "array".equals(columnEntity.getExtra())) {
                hasList = true;
            }

            columnEntityList.add(columnEntity);
        }
        tableEntity.setColumns(columnEntityList);

        //使用velocity资源加载
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        Map<String, Object> map = new HashMap();
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("hasList", hasList);

        //封装模板数据
        wrapperPropertiesData(map, config, tableEntity);

        List<String> mongoChildTemplates = getMongoChildTemplates(config.getString("template", "mongoSatellite"));

        VelocityContext context = new VelocityContext(map);
        String packageName = config.getString("package");
        String moduleName = config.getString("moduleName");
        for (String template : mongoChildTemplates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            //添加到流中
            try {
                zos.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassNameC(),
                        packageName, moduleName)));
                IOUtils.write(sw.toString(), zos, "UTF-8");
                IOUtils.closeQuietly(sw);
                zos.closeEntry();
            } catch (Exception e) {
                throw new RuntimeException("渲染模板失败:" + tableEntity.getTableName(), e);
            }
        }
    }

    /**
     * mongo表子类的模板
     */
    private static List<String> getMongoChildTemplates(String template) {
        List<String> templates = new ArrayList<>();
        template = "template-" + template + "/";
        templates.add(template + "MongoChildrenEntity.java.vm");
        return templates;
    }


}
